﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Globalization;
using System.Collections.Generic;
using DataAccess.DataObject;
using System.Security.Cryptography;

namespace EnmineKaitlin.admin
{
    public partial class users : Common.PageBase
    {
        const string module = "manage-user";
        int currentpage = 1;
        int pagesize = 10;
        string title = "";
        int group = 0;
        string status = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if(CheckPermission(module))
            {
            if (!IsPostBack)
            {
                try
                {
                    if (Request["uid"] != null && Request["uid"].ToString() != "")
                    {
                        pnlAddUser.Visible = false;
                        pnlDetailUser.Visible = true;
                        BindDetail(int.Parse(Request["uid"].ToString()));
                    }
                    else
                    {
                        ddlUserGroup.DataSource = _BGroup.Get(0);
                        ddlUserGroup.DataBind();                        
                    }
                    ddlUserGroupFilter.Items.Clear();
                    ddlUserGroupFilter.AppendDataBoundItems = true;
                    ListItem lst = new ListItem("Tất cả", "0");
                    ddlUserGroupFilter.Items.Add(lst);
                    ddlUserGroupFilter.DataSource = _BGroup.Get(0);
                    ddlUserGroupFilter.DataBind();

                    GetParam();
                    BindUser();
                }
                catch (Exception ex)
                {
                    Response.Redirect("~/admin");
                }
            }
            }
            else
            {                
                Response.Redirect("~/admin/permission-fail.aspx");
            }
        }
        protected void GetParam()
        {
            if (Request["currentpage"] != null && Request["currentpage"].ToString() != "")
            {
                currentpage = int.Parse(Request["currentpage"].ToString());
            }
            if (Request["s"] != null && Request["s"].ToString() != "")
            {
                title = Request["s"].ToString();
            }
            if (Request["status"] != null && Request["status"].ToString() != "")
            {
                status = Request["status"].ToString();
                ddlStatusFilter.SelectedValue = status;
                ddlStatusFilter.DataBind();
            }
            if (Request["group"] != null && Request["group"].ToString() != "")
            {
                group = int.Parse(Request["group"].ToString());
                ddlUserGroupFilter.SelectedValue = group.ToString();
                ddlUserGroupFilter.DataBind();
            }
        }
        protected void BindUser()
        {
            IList<OUser> lstUser = _BUser.Get(title, group, status,"FullName", "ASC", currentpage, pagesize);
            grvUser.DataSource = lstUser;
            grvUser.DataBind();
            if (lstUser.Count > 0)
            {
                ctlPagging.PageSize = pagesize;
                ctlPagging.ItemCount = (int)lstUser[0].TotalResult;
                string url = "status=" + status;
                if (title != "") { url += "&s=" + title; }
                if (group != 0) { url += "&group=" + group; }
                ctlPagging.QueryStringParameterName = url;
                ctlPagging.CurrentIndex = currentpage;
            }
        }
        protected void BindDetail(int UserID)
        {
            rptDetailUser.DataSource = _BUser.Get(UserID);
            rptDetailUser.DataBind();
        }
        protected void lbtFunction_Click(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "BunkFunction")
            {
                string function = ddlFunctionTop.SelectedValue;
                switch (function)
                {
                    case "delete":
                        foreach (GridViewRow grv in grvUser.Rows)
                        {
                            if (((CheckBox)grv.Cells[0].Controls[0]).Checked)
                            {
                                _BUser.Delete(grvUser.DataKeys[grv.RowIndex].Value.ToString());
                            }
                        }
                        break;
                    case "unlock":
                        foreach (GridViewRow grv in grvUser.Rows)
                        {
                            if (((CheckBox)grv.Cells[0].Controls[0]).Checked)
                            {
                                _BUser.UpdateStatus(grvUser.DataKeys[grv.RowIndex].Value.ToString(), "active");
                            }
                        }
                        break;
                    case "lock":
                        foreach (GridViewRow grv in grvUser.Rows)
                        {
                            if (((CheckBox)grv.Cells[0].Controls[0]).Checked)
                            {
                                _BUser.UpdateStatus(grvUser.DataKeys[grv.RowIndex].Value.ToString(), "lock");
                            }
                        }
                        break;
                }
                BindUser();
            }
        }
        protected void grvUser_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            AddCheckBoxAll(e);            
            BoundFunctionGridview(e);
        }
        protected void grvUser_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "delete")
            {
                if (_BUser.Delete(e.CommandArgument.ToString()))
                {
                    BindUser();
                }
            }
        }
        protected void btnAddUser_Click(object sender, EventArgs e)
        {
            _OUser.UserName = txtUserName.Text;
            using (MD5 md5Hash = MD5.Create())
            {
                _OUser.Password = GetMd5Hash(md5Hash, txtPassword.Text);
            }             
            _OUser.FullName = txtFullName.Text;
            _OUser.Email = txtEmail.Text;
            _OUser.PhoneNumber = txtPhone.Text;
            _OUser.Tel = txtTel.Text;
            _OUser.Gender = ddlGender.SelectedValue;
            _OUser.BirthDay = DateTime.Parse(txtBirthday.Text, culture, DateTimeStyles.NoCurrentDateDefault);
            _OUser.Address = txtAddress.Text;
            _OUser.Position = txtPosition.Text;
            _OUser.Status = ddlStatus.SelectedValue;
            _OUser.IDDepartment = 1;
            _OUser.IDGroup = int.Parse(ddlUserGroup.SelectedValue);
            if (_BUser.Add(_OUser))
            {
                BindUser();
                txtUserName.Text = "";
                txtPassword.Text = "";
                txtFullName.Text="";
                txtEmail.Text = "";
                txtPhone.Text="";
                txtTel.Text="";
                txtBirthday.Text = "";
                txtAddress.Text="";
                txtPosition.Text="";
            }
        }
        protected void btnFilter_Command(object sender, CommandEventArgs e)
        {            
            if (txtKeyWord.Text == "Nhập từ khóa")
            {
                txtKeyWord.Text = "";
            }
            title = txtKeyWord.Text;
            if (ddlUserGroupFilter.SelectedValue != "")
            {
                group = int.Parse(ddlUserGroupFilter.SelectedValue);
            }
            status = ddlStatusFilter.SelectedValue;
            BindUser();
        }
        protected IList<OGroup> BindGroup()
        {
            return _BGroup.Get(0);
        }
        protected string GetGroup(int UserID)
        {
            string group = "";
            _OUserGroup.IDGroup = 0;
            _OUserGroup.IDUser = UserID;
            IList<OUserGroup> lstUserGroup=_BUserGroup.Get(_OUserGroup);
            for (int i = 0; i < lstUserGroup.Count; i++)
            {
                group += _BGroup.Get(lstUserGroup[i].IDGroup)[0].Name+",";                
            }
            group = group.Substring(0, group.Length - 1);
            return group;
        }

        protected void rptDetailUser_Update(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Update")
            {                
                _OUser.UserName = ((TextBox)e.Item.FindControl("txtUserName")).Text;
                if (((TextBox)e.Item.FindControl("txtPassword")).Text != "")
                {
                    using (MD5 md5Hash = MD5.Create())
                    {
                        _OUser.Password = GetMd5Hash(md5Hash, ((TextBox)e.Item.FindControl("txtPassword")).Text);                        
                    }                    
                }
                else {
                    _OUser.Password = "";
                }
                _OUser.FullName = ((TextBox)e.Item.FindControl("txtFullName")).Text;
                _OUser.Email = ((TextBox)e.Item.FindControl("txtEmail")).Text;
                _OUser.PhoneNumber = ((TextBox)e.Item.FindControl("txtPhone")).Text;
                _OUser.Tel = ((TextBox)e.Item.FindControl("txtTel")).Text;
                _OUser.Gender = ((DropDownList)e.Item.FindControl("ddlGender")).SelectedValue;
                _OUser.BirthDay = DateTime.Parse(((TextBox)e.Item.FindControl("txtBirthday")).Text, culture, DateTimeStyles.NoCurrentDateDefault);
                _OUser.Address = ((TextBox)e.Item.FindControl("txtAddress")).Text;
                _OUser.Position = ((TextBox)e.Item.FindControl("txtPosition")).Text;
                _OUser.Status = ((DropDownList)e.Item.FindControl("ddlStatus")).SelectedValue;                
                _OUser.IDGroup = int.Parse(((DropDownList)e.Item.FindControl("ddlUserGroup")).SelectedValue);
                if (_BUser.Update(_OUser))
                {
                    RegisterClientScriptBlock("NOTE", "<script>alert('Cập nhật thành công !');</script>");
                    BindUser();
                }
            }
        }

        protected void grvUser_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

        }
    }
}
